package com.example.publice.aspect;

import com.example.publice.aspect.annotation.DataValidate;
import com.example.publice.validations.DataValidator;
import com.example.util.SpringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 数据验证
 */
@Aspect
@Component
public class DataValidateAspect {


    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && (" +
            "@annotation(org.springframework.web.bind.annotation.GetMapping) ||" +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) ||" +
            "@annotation(org.springframework.web.bind.annotation.PutMapping) ||" +
            "@annotation(org.springframework.web.bind.annotation.DeleteMapping) ||" +
            "@annotation(org.springframework.web.bind.annotation.RequestMapping))")
    public void validatePointCut(){}

    @Around("validatePointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        Object[] args = joinPoint.getArgs();
        List<Object> listArgs = new ArrayList<>();
        for(Object obj:args) {
            listArgs.add(obj);
        }
        Annotation[] annotations = targetMethod.getDeclaredAnnotations();
        for(Annotation annotation : annotations) {
            if(annotation instanceof DataValidate) {
                Class<?>[] clazzArray = ((DataValidate) annotation).value();
                for(Class<?> clazz: clazzArray) {
                    DataValidator validator = (DataValidator) SpringUtils.getBean(clazz);
                    validator.init(listArgs);
                    validator.validate();
                }
            }
        }
       return  joinPoint.proceed();
    }







}
